<?php
namespace App\Controller;

use App\Model\User;
use App\Model\Gallary;
use lib\view;

class AuthenticateController
{
    public function register()
    {
        $inputBag = isset($_SESSION['input_bag']) ? $_SESSION['input_bag'] : ['id' => '', 'email' => '', 'userName' => ''];
        $errorBag = isset($_SESSION['error_bag']) ? $_SESSION['error_bag'] : ['id' => '', 'email' => '', 'userName' => '', 'password' => '', 'password_confirm' => ''];

        // 销毁session中的错误数据包 （错误数据包是一次性的）
        unset($_SESSION['input_bag']);
        unset($_SESSION['error_bag']);

        return $this->view('auth.register', [
            'inputBag' => $inputBag,
            'errorBag' => $errorBag
        ]);
    }

    public function doRegister()
    {
        $user = User::newUser($_POST);
        if (empty($user)) {
            header('Location:' . url('auth/register'));
            return;
        }
        $user->password = password_hash($user->password, PASSWORD_BCRYPT);
        // 对象持久化
        $user->save();
        header('Location:' . url('auth/signin'));
    }

    public function signin()
    {
        $errorBag = isset($_SESSION['error_bag']) ? $_SESSION['error_bag'] : ['error' => ''];

        // 销毁session中的错误数据包 （错误数据包是一次性的）
        unset($_SESSION['error_bag']);
        return $this->view('auth.signin', [
            'errorBag' => $errorBag
        ]);
    }

    public function auth()
    {
        $email = $_POST['email'];
        $inputPassword = $_POST['password'];

        $user = User::find(['email' => $email]);

        if (!empty($user)) {
            if (password_verify($inputPassword, $user->password)) {
                $_SESSION['user'] = $user;
                header('Location:' . url('index'));
                return;
            }
        }

        $_SESSION['error_bag'] = ['error' => '用户名或密码错误'];
        header('Location:' . url('auth/signin'));
    }

    private function view($viewName, Array $data = [])
    {
        return new View($viewName, $data);
    }
}